package com.wu.controller;

import com.wu.constant.Constant;
import com.wu.error.BusinessException;
import com.wu.error.EnumBusinessError;
import com.wu.response.CommonReturnType;
import com.wu.service.UsersService;
import com.wu.util.RedisUtil;
import com.wu.util.SendSmsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-20 19:30
 */
@RestController
@Api(tags = "短信接口")
public class SendSmsController {
    @Autowired
    private SendSmsUtils sendSmsUtils;

    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 发送短信的接口
     *
     * @param telPhone
     * @return
     * @throws BusinessException
     */
    @ApiOperation(value = "发送短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "telPhone", value = "手机号", required = true, dataTypeClass = String.class)
    })
    @RequestMapping(value = "/getSMS", method = RequestMethod.POST)
    public CommonReturnType getSMS(@RequestParam("telPhone") String telPhone) throws BusinessException {
        //先验证手机号是否存在
        usersService.telPhoneIsOk(telPhone);

        try {
            //单纯的就是为了测试能不能连接redis
            redisUtil.hasKey("test");
        } catch (Exception e) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "短信发送失败，redis连接失败，请联系管理员");
        }

        //发送短信
        if (!redisUtil.hasKey(telPhone)) {
            //生成验证码，并 存储到redis中
            String code = UUID.randomUUID().toString().substring(0, 5);
            HashMap<String, Object> map = new HashMap();
            map.put(Constant.CODE, code);
            boolean isSend = sendSmsUtils.sendSms(telPhone, map);
            if (isSend) {
                //将该用户的验证码加入到redis并设置有效时间为5分钟
                redisTemplate.opsForValue().set(telPhone, code, 5, TimeUnit.MINUTES);
            }
        } else {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "请务重复发送");
        }
        return CommonReturnType.create(null);
    }
}
